import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import Category from '../views/Category.vue';
import Product from '../views/Product.vue';
import Mine from '../views/Mine.vue';
import Order from '../views/Order.vue';
import OrderPreview from '../views/OrderPreview.vue';
import OrderDetail from '../views/OrderDetail.vue';
import Account from '../views/Account.vue';
import ChangePassword from '../views/ChangePassword.vue';
import Address from '../views/Address.vue';
import AddressDetail from '../views/AddressDetail.vue';
import About from '../views/About.vue';
import Cart from '../views/Cart.vue';
import ProductDetail from '../views/ProductDetail.vue';
import store, { IS_AUTHENTICATED } from '@/store';

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: "/home"
  },
  {
    path: '/home',
    name: "Home",
    component: Home,
    meta: {
      index: 1
    }
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/register",
    name: "Register",
    component: Register,
  },
  {
    path: "/category",
    name: "Category",
    component: Category,
  },
  {
    path: "/product",
    name: "Product",
    component: Product,
  },
  {
    path: "/product-detail",
    name: "ProductDetail",
    component: ProductDetail,
  },
  {
    path: "/cart",
    name: "Cart",
    component: Cart,
  },
  {
    path: "/order-preview",
    name: "OrderPreview",
    component: OrderPreview,
  },
  {
    path: "/order-detail",
    name: "OrderDetail",
    component: OrderDetail,
  },
  {
    path: "/mine",
    name: "Mine",
    component: Mine,
  },
  {
    path: "/order",
    name: "Order",
    component: Order,
  },
  {
    path: "/account",
    name: "Account",
    component: Account,
  },
  {
    path: "/change-password",
    name: "ChangePassword",
    component: ChangePassword,
  },
  {
    path: "/about",
    name: "About",
    component: About,
  },
  {
    path: "/address",
    name: "Address",
    component: Address,
  },
  {
    path: "/address-detail",
    name: "AddressDetail",
    component: AddressDetail,
  },
  {
    path: "/about",
    name: "About",
    component: About,
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes
});

router.beforeEach((to, from, next) => {
  const isAuthenticated: boolean = store.getters[IS_AUTHENTICATED];

  const whiteList = [
    "/login",
    "/register",
    "/home",
    "/product-detail",
  ];

  if (whiteList.includes(to.path)) {
    next();
  } else {
    if (isAuthenticated) {
      next()
    } else {
      next('/login')
    }

  }
})

export default router;
